package org.example.csa.rest;

import cn.hutool.http.HttpStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 公共返回体-泛型类
 *
 * @param <T> 泛型T
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class AjaxResponse<T> implements Serializable {

    private String code;
    private String msg;
    private T data;


    public static AjaxResponse success(String msgStr) {
        return AjaxResponse.builder()
                .code(String.valueOf(HttpStatus.HTTP_OK))
                .msg(msgStr)
                .data(null)
                .build();
    }

    public static AjaxResponse success() {
        return AjaxResponse.builder()
                .code(String.valueOf(HttpStatus.HTTP_OK))
                .msg("操作成功")
                .data(null)
                .build();
    }


    public static <T> AjaxResponse<T> success(T dat) {
        return restResult(dat, String.valueOf(HttpStatus.HTTP_OK), "操作成功");
    }


    public static <T> AjaxResponse<T> success(String msgStr, T dat) {
        return restResult(dat, String.valueOf(HttpStatus.HTTP_OK), msgStr);
    }

    public static AjaxResponse error(String msgStr) {
        return AjaxResponse.builder()
                .code(String.valueOf(HttpStatus.HTTP_INTERNAL_ERROR))
                .msg(msgStr)
                .data(null)
                .build();
    }


    public static AjaxResponse error() {
        return AjaxResponse.builder()
                .code(String.valueOf(HttpStatus.HTTP_INTERNAL_ERROR))
                .msg("操作失败")
                .data(null)
                .build();
    }


    public static <T> AjaxResponse<T> error(T dat) {
        return restResult(dat, String.valueOf(HttpStatus.HTTP_INTERNAL_ERROR), "操作失败");


    }

    public static <T> AjaxResponse<T> error(String msgStr, T dat) {
        return restResult(dat, String.valueOf(HttpStatus.HTTP_INTERNAL_ERROR), msgStr);

    }


    /**
     * 通用自定义返回
     *
     * @param dat
     * @param code
     * @param msgStr
     * @return
     */
    public static <T> AjaxResponse<T> general(T dat, String code, String msgStr) {
        return restResult(dat, code, msgStr);
    }


    private static <T> AjaxResponse<T> restResult(T data, String code, String msg) {
        AjaxResponse<T> apiResult = new AjaxResponse<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }
}
